<template>
<el-container style="height: 500px; border: 1px solid #eee">
    <el-aside width="280px" class="left-tree">
      <el-tree lazy node-key="id" ref="tree" :props="props" :load="loadNode" :highlight-current="true" :expand-on-click-node="false" @node-click="handleNodeClick" />
    </el-aside>
    <el-main style="padding:5px">
      <os-table autoHeight stripe :autoLoad="false" :otherSearch="otherSearch" action="system/positionPage" :columns="columns" :form="form" ref='osTable'  v-loading="loading" :btn="btn" size="small" border></os-table>
  </el-main>
  </el-container>
</template>

<script>
export default {
  name: 'positionPage',
  data () {
    return {
      props: {
        label: 'orgName',
        children: 'children',
        isLeaf: 'leaf'
      },
      form: {
        rule: [
          { type: 'Input', title: '岗位编码', field: 'positionCode' },
          { type: 'Input', title: '岗位名称', field: 'positionName' },
          { type: 'el-button', field: 'search', props: { type: 'primary' }, children: ['查询'], emit: ['click'] },
          { type: 'el-button', field: 'clear', props: { type: 'primary' }, children: ['清空'], emit: ['click'] }
        ]
      },
      btn: [
        { text: '新增', cb: cb => this.onAdd() }
      ],
      columns: [
        // {label: 'id', prop: 'id'},
        { label: '岗位编码', prop: 'positionCode' },
        { label: '岗位名称', prop: 'positionName' },
        {
          label: '是否有效',
          prop: 'validation',
          formatter: (row) => {
            return this.$c.dictCode.validation.filter(i => {
              return i.value === row.validation
            })[0].label
          }
        },
        {
          label: '操作',
          prop: 'action',
          renderCell: (data) => (
            <div>
              <el-button
                type="text"
                size="mini"
                onClick={() => this.onEdit(data)}
              >
                编辑
              </el-button>
              <el-button
                type="text"
                size="mini"
                onClick={() => this.onDel(data)}
              >
                删除
              </el-button>
            </div>
          )
        }
      ],
      fApi: null,
      rule: [
        { type: 'hidden', title: 'id', field: 'id' },
        { type: 'hidden', title: 'orgId', field: 'orgId' },
        { type: 'Input', title: '部门', field: 'orgName' },
        { type: 'Input', title: '岗位编码', field: 'positionCode', validate: [this.$v.required()] },
        { type: 'Input', title: '岗位名称', field: 'positionName', validate: [this.$v.required()] },
        { type: 'Radio', title: '是否有效', field: 'validation' },
        {
          type: 'OsSelect',
          title: '角色',
          field: 'roles',
          props: { name: 'roles', multiple: true, filterable: true }, // 是否可搜索
          value: [],
          options: [] // 这里必须要有，不然不会显示结果
          // validate: [this.$v.required('array')]
        },
        { type: 'Input', title: '描述', field: 'description', props: { type: 'textarea' }, col: { span: 24 } }
      ],
      options: {
        ...this.$utils.formOptions(100, 24),
        mounted: $f => {
          this.$utils.setOptions($f, 'roles', 'roleName', 'id', 'system/roleAll')
          this.$utils.updateFormOptions($f, 'validation', this.$c.dictCode.validation)
        }
      },
      otherSearch: { orgId: '-1' },
      nodeData: {}, // 点击选中的节点数据,主要用于增、修、删
      loading: false
    }
  },
  methods: {
    /** 获取数据 */
    async loadNode (node, resolve) {
      if (node.level === 0) {
        return this.getTreeData(resolve, node)
      }
      this.getTreeData(resolve, node)
      return resolve([]) // 加上这个，防止在该节点没有子节点时一直转圈的问题发生。
    },
    async getTreeData (resolve, node) {
      let parentId = '-1'
      if (node?.data) {
        parentId = node.data.id
      }
      const { data } = await this.$store.dispatch('system/getOrgByParentId', { parentId: parentId })
      if (data && parentId === '-1') {
        this.nodeData = data[0]
        this.loadTableData(this.nodeData)
      }
      resolve(data)
    },
    handleNodeClick (data, node) {
      this.nodeData = data
      this.loadTableData(data)
    },
    loadTableData (data) {
      if (data) {
        this.otherSearch.orgId = data.id
      } else {
        this.otherSearch.orgId = '-1'
      }
      this.$refs.osTable.getData()
    },
    onAdd (row = null) {
      if (!this.nodeData) {
        this.$utils.message.warning('请选择组织机构！')
        return
      }
      this.onHandle()
    },
    async onEdit ({ row }) {
      this.loading = true
      const { data } = await this.$store.dispatch('system/getRolesByPositionId', row.id)
      this.loading = false
      row.roles = data.map(r => r.id)
      this.onHandle(row)
    },
    onHandle (row = { roles: [] }) {
      const btn = [{ text: '保存', loading: true, cb: cb => this.save(cb, row) }]
      this.$utils.dialog(`${row.id ? '编辑' : '添加'}岗位`, <form-create vModel={this.fApi} rule={this.rule} option={this.options}/>,
        { btn, width: '60%' })
      this.$nextTick(() => {
        this.$f.resetFields(this.fApi, row)
        const node = this.nodeData
        this.fApi.setValue({ orgId: node.id, orgName: node.orgName })
        this.fApi.disabled(true, 'orgName')
        if (row.id) {
          // this.fApi.setValue(o)
        } else {
          this.fApi.setValue({ validation: '1' })// 默认列表
        }
      })
    },
    save (cb, row) {
      this.fApi.validate(async (valid) => {
        cb()
        if (valid) {
          const formData = this.fApi.formData()
          const action = row.id ? 'system/positionUpdate' : 'system/positionInsert'
          const { error } = await this.$store.dispatch(action, formData)
          if (!error) {
            this.$utils.message.success('保存成功')
            this.fApi.resetFields()
            this.$utils.hideDialog()
            this.$refs.osTable.getData()
          }
        }
      })
    },

    async onDel ({ row }) {
      const re = await this.$utils.confirm('确定要删除吗？')
      if (!re) return
      const { error } = await this.$store.dispatch('system/positionDelete', row.id)
      if (!error) {
        this.$utils.message.success('删除成功')
        this.$refs.osTable.getData()
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.left-tree {
  background-color: #fff ;
  border : 1px solid #eee ;
  margin: 5px;
  }
</style>
